<template>
  <div>
    <a-button type="primary" @click="openAdd" style="margin-bottom: 16px;">新增客房</a-button>
    <a-table :columns="columns" :data-source="data" row-key="id" :loading="loading">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button type="link" @click="openEdit(record)">编辑</a-button>
          <a-popconfirm title="确定删除吗？" @confirm="() => handleDelete(record.id)">
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
        <template v-if="column.key === 'tags'">
          <a-tag v-for="tag in record.tags" :key="tag" color="blue">{{ tag }}</a-tag>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="showModal" :title="isEdit ? '编辑客房' : '新增客房'" @ok="handleOk" @cancel="handleCancel" width="800px">
      <a-form :model="form" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="房间名称">
              <a-input v-model:value="form.name" placeholder="例如：豪华海景房" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="房间号">
              <a-input v-model:value="form.number" placeholder="例如：101" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="类型">
              <a-input v-model:value="form.type" placeholder="例如：单人间/双人间" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="价格">
              <a-input-number v-model:value="form.price" style="width:100%" addonAfter="元/晚" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="数量">
              <a-input-number v-model:value="form.count" style="width:100%" min="1" @change="onCountChange" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="容纳人数">
              <a-input-number v-model:value="form.capacity" style="width:100%" min="1" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="房间面积">
              <a-input-number v-model:value="form.size" style="width:100%" min="1" addonAfter="㎡" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="床型">
              <a-select v-model:value="form.bedType">
                <a-select-option value="单人床">单人床</a-select-option>
                <a-select-option value="双人床">双人床</a-select-option>
                <a-select-option value="大床">大床</a-select-option>
                <a-select-option value="特大床">特大床</a-select-option>
                <a-select-option value="双床">双床</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="标签">
          <a-select v-model:value="form.tags" mode="tags" placeholder="添加标签，如：海景、高层、禁烟">
            <a-select-option value="海景">海景</a-select-option>
            <a-select-option value="高层">高层</a-select-option>
            <a-select-option value="禁烟">禁烟</a-select-option>
            <a-select-option value="含早">含早</a-select-option>
            <a-select-option value="无障碍">无障碍</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="设施">
          <a-checkbox-group v-model:value="form.amenities">
            <a-checkbox value="免费WiFi">免费WiFi</a-checkbox>
            <a-checkbox value="空调">空调</a-checkbox>
            <a-checkbox value="平板电视">平板电视</a-checkbox>
            <a-checkbox value="咖啡机">咖啡机</a-checkbox>
            <a-checkbox value="迷你吧">迷你吧</a-checkbox>
            <a-checkbox value="浴缸">浴缸</a-checkbox>
            <a-checkbox value="吹风机">吹风机</a-checkbox>
          </a-checkbox-group>
        </a-form-item>

        <a-form-item label="具体房间号">
          <div v-for="(room, idx) in form.roomNumbers" :key="idx" style="margin-bottom: 8px;">
            <a-input v-model:value="form.roomNumbers[idx]" :placeholder="`房间号${idx+1}`" />
          </div>
        </a-form-item>

        <a-form-item label="封面图片">
          <a-upload
            list-type="picture-card"
            :file-list="form.image ? [form.image] : []"
            :before-upload="beforePhotoUpload"
            :on-remove="handleCoverRemove"
            :custom-request="uploadCoverImage"
            @change="handleCoverChange"
            :maxCount="1"
          >
            <div v-if="!form.image">
              <plus-outlined />
              <div style="margin-top: 8px;">上传封面</div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item label="客房照片集">
          <a-upload
            list-type="picture-card"
            :file-list="form.gallery || []"
            :before-upload="beforePhotoUpload"
            :on-remove="handleGalleryRemove"
            :custom-request="uploadGalleryImage"
            @change="handleGalleryChange"
            multiple
          >
            <plus-outlined />
            <div style="margin-top: 8px;">上传</div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { apiGetRoomsList, apiAddRoom, apiUpdateRoom, apiDeleteRoom, apiUploadRoomImage, apiGetHotelInfo } from '@/api/admin-api';
import { useHotelStore } from '@/stores/hotelStrore';

interface Room {
  id: number;
  hotelId: number | string;
  number: string;
  name: string;
  type: string;
  price: number;
  count: number;
  capacity: number;
  size: number;
  bedType: string;
  tags: string[];
  amenities: string[];
  roomNumbers: string[];
  image: any;
  gallery: any[];
  imageUrl?: string;
  galleryUrls?: string[];
}

const showModal = ref(false);
const isEdit = ref(false);
const editId = ref<number | null>(null);
const loading = ref(false);
const hotelStore = useHotelStore();
const form = ref<Room>({
  id: 0,
  hotelId: 0,
  number: '',
  name: '',
  type: '',
  price: 0,
  count: 1,
  capacity: 2,
  size: 30,
  bedType: '大床',
  tags: [],
  amenities: [],
  roomNumbers: [''],
  image: null,
  gallery: []
});

const data = ref<Room[]>([]);

const columns = [
  { title: '房间名称', dataIndex: 'name', key: 'name' },
  { title: '房间号', dataIndex: 'number', key: 'number' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '价格', dataIndex: 'price', key: 'price' },
  { title: '容量', dataIndex: 'capacity', key: 'capacity' },
  { title: '床型', dataIndex: 'bedType', key: 'bedType' },
  { title: '标签', key: 'tags' },
  { title: '操作', key: 'action' }
];

// 获取客房列表
async function fetchRoomsList() {
  if (!hotelStore.safeHotelId) {
    message.error('酒店ID未设置，无法加载客房信息');
    return;
  }
  
  loading.value = true;
  try {
    const res: any = await apiGetRoomsList(hotelStore.safeHotelId);
    if (res.code === 200) {
      data.value = res.data.records.map((room: any) => {
        return {
          ...room,
          image: room.imageUrl ? {
            uid: '-1',
            name: 'cover.jpg',
            status: 'done',
            url: room.imageUrl
          } : null,
          gallery: (room.galleryUrls || []).map((url: string, index: number) => ({
            uid: `-${index + 1}`,
            name: `gallery${index + 1}.jpg`,
            status: 'done',
            url: url
          }))
        };
      });
    } else {
      message.error(res.msg || '获取客房列表失败');
    }
  } catch (error) {
    console.error('获取客房列表出错:', error);
    message.error('获取客房列表失败');
  } finally {
    loading.value = false;
  }
}

// 组件挂载时获取酒店信息和客房列表
onMounted(async () => {
  if (!hotelStore.isInitialized) {
    await hotelStore.getHotelInfo();
  }
  
  if (hotelStore.safeHotelId) {
    fetchRoomsList();
  } else {
    message.warning('未找到酒店ID，无法加载客房信息');
  }
});

function openAdd() {
  isEdit.value = false;
  showModal.value = true;
  form.value = {
    id: 0,
    hotelId: hotelStore.safeHotelId,
    number: '',
    name: '',
    type: '',
    price: 0,
    count: 1,
    capacity: 2,
    size: 30,
    bedType: '大床',
    tags: [],
    amenities: [],
    roomNumbers: [''],
    image: null,
    gallery: []
  };
  editId.value = null;
}

function openEdit(record: Room) {
  isEdit.value = true;
  showModal.value = true;
  form.value = { 
    ...record, 
    hotelId: hotelStore.safeHotelId,
    gallery: record.gallery ? [...record.gallery] : [], 
    roomNumbers: record.roomNumbers ? [...record.roomNumbers] : [],
    image: record.image ? {...record.image} : null,
    tags: record.tags ? [...record.tags] : [],
    amenities: record.amenities ? [...record.amenities] : []
  };
  editId.value = record.id;
}

function onCountChange(val: number) {
  if (val < 1) return;
  const base = form.value.number || '';
  const oldRooms = form.value.roomNumbers || [];
  const newRooms = [];
  for (let i = 0; i < val; i++) {
    newRooms.push(oldRooms[i] || (base ? `${base}-${i+1}` : ''));
  }
  form.value.roomNumbers = newRooms;
}

watch(() => form.value.count, (val) => onCountChange(val));

function beforePhotoUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  const isLt10M = file.size / 1024 / 1024 < 10;
  
  if (!isImage) {
    message.error('只能上传图片文件');
    return false;
  }
  
  if (!isLt10M) {
    message.error('图片大小不能超过10MB');
    return false;
  }
  
  return isImage && isLt10M;
}

// 上传封面图片
function uploadCoverImage({ file, onSuccess, onError }: any) {
  const formData = new FormData();
  formData.append('file', file);
  
  apiUploadRoomImage(formData)
    .then((res: any) => {
      if (res.code === 200) {
        onSuccess();
        form.value.imageUrl = res.data;
      } else {
        onError();
        message.error(res.msg || '上传失败');
      }
    })
    .catch(err => {
      console.error('上传图片出错:', err);
      onError();
      message.error('上传失败');
    });
}

// 上传相册图片
function uploadGalleryImage({ file, onSuccess, onError }: any) {
  const formData = new FormData();
  formData.append('file', file);
  
  apiUploadRoomImage(formData)
    .then((res: any) => {
      if (res.code === 200) {
        onSuccess();
        if (!form.value.galleryUrls) form.value.galleryUrls = [];
        form.value.galleryUrls.push(res.data);
      } else {
        onError();
        message.error(res.msg || '上传失败');
      }
    })
    .catch(err => {
      console.error('上传图片出错:', err);
      onError();
      message.error('上传失败');
    });
}

function handleCoverRemove() {
  form.value.image = null;
  form.value.imageUrl = '';
}

function handleCoverChange({ fileList }: any) {
  if (fileList.length > 0) {
    const file = fileList[0];
    form.value.image = {
      ...file,
      url: file.url || (file.originFileObj ? URL.createObjectURL(file.originFileObj) : ''),
      uid: file.uid
    };
  } else {
    form.value.image = null;
    form.value.imageUrl = '';
  }
}

function handleGalleryChange({ fileList }: any) {
  form.value.gallery = fileList.map((file: any) => ({
    ...file,
    url: file.url || (file.originFileObj ? URL.createObjectURL(file.originFileObj) : ''),
    uid: file.uid
  }));
}

function handleGalleryRemove(file: any) {
  // 从gallery数组中移除文件
  form.value.gallery = (form.value.gallery || []).filter((f: any) => f.uid !== file.uid);
  
  // 从galleryUrls数组中移除对应的URL
  if (form.value.galleryUrls && form.value.galleryUrls.length > 0) {
    // 找到要删除的图片URL的索引
    const fileUrl = file.url || '';
    const urlIndex = form.value.galleryUrls.findIndex((url: string) => url === fileUrl);
    
    // 如果找到了对应的URL，则从数组中删除
    if (urlIndex !== -1) {
      form.value.galleryUrls.splice(urlIndex, 1);
    }
  }
}

async function handleOk() {
  if (!hotelStore.safeHotelId) {
    message.error('酒店ID未设置，无法保存客房信息');
    return;
  }

  // 验证必填字段
  if (!form.value.name) {
    message.error('请输入房间名称');
    return;
  }

  if (!form.value.price || form.value.price <= 0) {
    message.error('请输入有效的房间价格');
    return;
  }

  // 准备提交的数据
  const roomData = {
    ...form.value,
    hotelId: hotelStore.safeHotelId,
    // 处理图片URL
    imageUrl: form.value.imageUrl || (form.value.image && form.value.image.url ? form.value.image.url : ''),
    // 处理图片集合URL
    galleryUrls: form.value.galleryUrls || (form.value.gallery || []).map((item: any) => item.url).filter(Boolean)
  };
  
  // 删除不需要的字段
  const submitData = { ...roomData };
  delete (submitData as any).image;
  delete (submitData as any).gallery;
  
  try {
    if (isEdit.value && editId.value !== null) {
      // 更新客房
      const res: any = await apiUpdateRoom(submitData);
      if (res.code === 200) {
        message.success('更新成功');
        showModal.value = false;
        fetchRoomsList(); // 重新获取列表
      } else {
        message.error(res.msg || '更新失败');
      }
    } else {
      // 添加客房
      const res: any = await apiAddRoom(submitData);
      if (res.code === 200) {
        message.success('添加成功');
        showModal.value = false;
        fetchRoomsList(); // 重新获取列表
      } else {
        message.error(res.msg || '添加失败');
      }
    }
  } catch (error) {
    console.error('操作失败:', error);
    message.error('操作失败，请重试');
  }
}

function handleCancel() {
  showModal.value = false;
}

async function handleDelete(id: number) {
  try {
    const res: any = await apiDeleteRoom(id);
    if (res.code === 200) {
      message.success('删除成功');
      fetchRoomsList(); // 重新获取列表
    } else {
      message.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    message.error('删除失败，请重试');
  }
}
</script> 